#!/usr/bin/env python
import httplib2
import logging
import os
import pickle

from apiclient.discovery import build
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.client import OAuth2WebServerFlow
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import login_required

import wsgiref.handlers

from authorization import AuthorizationHandler
from buzz import BuzzOAuthHandler
from twitter import TwitterAuthHandler
from microsyndutils import Session
from microsyndutils import Shout
from microsyndutils import UserAccount

class MainHandler(webapp.RequestHandler):
    @login_required
    def get(self):
        user = users.get_current_user()
        user_account = UserAccount.get_by_key_name(user.user_id())
        if user_account is None:
            user_account = UserAccount(
                    key_name=user.user_id(),
                    user=user)
            user_account.put()

        path = os.path.join(os.path.dirname(__file__), 'main.html')
        logout = users.create_logout_url('/')
        shouts = db.GqlQuery(
                'SELECT * FROM Shout '
                'ORDER BY when DESC')
        values = {
                'user': user.nickname(),
                'shouts': shouts,
                'logout': logout,
                # check the checkboxes as the user did last time
                'checkbuzz': 'checked' if user_account.buzz else '',
                'checkfacebook': 'checked' if user_account.facebook else '',
                'checkweibo': 'checked' if user_account.weibo else '',
                'checktwitter': 'checked' if user_account.twitter else ''
                }
        self.response.out.write(template.render(path, values))

    def post(self):
        user = users.get_current_user()
        user_account = UserAccount.get_by_key_name(user.user_id())
        if user_account is None:
            assert False, 'how come we do not recognize a posting user?'
         
        msg = self.request.get('message')
        
        # remember the services the user selected
        if self.request.get('buzz') == 'yes':
            user_account.buzz = True
        else:
            user_account.buzz = False
        if self.request.get('facebook') == 'yes':
            user_account.facebook = True
        else:
            user_account.facebook = False
        if self.request.get('weibo') == 'yes':
            user_account.weibo = True
        else:
            user_account.weibo = False
        if self.request.get('twitter') == 'yes':
            user_account.twitter = True
        else:
            user_account.twitter = False
        user_account.put()
            
        if msg is not None and len(msg) != 0:
            targets = {}
            targets['buzz'] = self.request.get('buzz')
            targets['facebook'] = self.request.get('facebook')
            targets['weibo'] = self.request.get('weibo')
            targets['twitter'] = self.request.get('twitter')

            session = Session(targets, msg)
            memcache.set('session' + user.user_id(), pickle.dumps(session))

            self.redirect('/authorization')
        else:
            self.redirect('/')

def main():
    app = webapp.WSGIApplication(
            [('/', MainHandler),
             ('/authorization', AuthorizationHandler),
             ('/buzz_auth_return', BuzzOAuthHandler),
             ('/twitter_auth', TwitterAuthHandler),
             ], 
            debug=True)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()
